package cn.jdy.plugins.wap;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.MemberService;

/**
 * 会员登录控制类
 * 
 * @author yangyi
 * @date : 2014-03-15
 */
@Controller
@RequestMapping("/login")
public class LoginCtrl extends BaseCtrl {
	public static final String msg_00 = "00";// 服务器忙，请稍后再试!
	public static final String msg_01 = "01";// 请输入您的用户名或手机号或邮箱!
	public static final String msg_02 = "02";// 请输入您的密码!
	public static final String msg_03 = "03";// 请输入验证码!
	public static final String msg_04 = "04";// 验证码错误，请重新输入!
	public static final String msg_05 = "05";// 您输入的用户不存在，请重新输入!
	public static final String msg_06 = "06";// 您的账号已经被锁定,24小时内禁止登录!
	public static final String msg_07 = "07";// 您的帐号未被激活，请问是否现在激活!
	public static final String msg_08 = "08";// 密码错误，连续输入5次错误密码帐户 需要输入验证码!
	public static final String msg_09 = "09";// 您的账号已经被锁定，请联系客服解决!
	public static final String msg_10 = "10";// 您输入的账户已经被禁用，请联系客服解决!
	public static final String msg_99 = "99";// 登录成功!
	@Autowired
	private MemberService memberService;// 会员分类业务处理类

	/**
	 * 登陆初始化
	 */
	@RequestMapping("")
	public ModelAndView forLogin() {
		ModelAndView mv = new ModelAndView(super.t + "/login.jsp");
		return mv;
	}

	/**
	 * 用户登录页面
	 */
	@RequestMapping("/loginIndex")
	public ModelAndView loginIndex() {
		ModelAndView mv = new ModelAndView("/login.jsp");
		return mv;
	}

	/**
	 * 汉水商城登陆
	 * 
	 * @param loginname
	 * @param loginpwd
	 * @param response
	 * @return
	 */
	@RequestMapping("/loginOk")
	public ModelAndView login1(String loginname, String loginpwd,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		String str = "";
		try {
			Object obj = session.getAttribute("user:" + loginname
					+ ":passworderrorcount");
			int errorcount = 0;
			if (!StringUtil.isNullOrEmpty(obj)) {
				errorcount = (Integer) obj;
			}
			/* 校验输入信息是否合法 */
			// memberService
			// str = checkUserLogin(loginname, loginpwd, code);
			if ("".equals(str)) {
				Member member = memberService.findMemberByUsername(loginname);

				if (null != member) {
					// if("1".equals(member.getUserType())){// 移动端 暂时不支持企业用户登录
					// mv.addObject("msg", "此版本暂不支持企业会员访问");//
					// mv.setViewName(super.t + "/loginOk");
					// return mv;
					// }
					if (SafeUtil.md5(loginpwd).substring(8, 16)
							.equals(member.getPassword())) {
						if ("0".equals(member.getStatus())) {
							/* 登录成功 保存会员信息到session 并 返回 */
							String mobile = member.getMobile();
							if (!StringUtil.isNullOrEmpty(mobile)) {
								mobile = mobile.substring(0, 3)
										+ "*****"
										+ mobile.substring(mobile.length() - 3,
												mobile.length());
								member.setMobile(mobile);
							}

							session.setAttribute("user", member);
							String date;
							if (member.getLastLoginDate() != null
									&& (date = member.getLastLoginDate()
											.replaceAll("[^\\d]", "")).length() >= 8
									&& Integer.parseInt(date.substring(0, 8)) < Integer
											.parseInt(DateUtil
													.getCurrentDate(DateUtil._DEFAULT3)))
								memberService
										.updateMoney(
												member.getId(),
												"1".equals(member.getApprove()) ? GlobalConstant.SMONEY_LOGIN_APPROVED
														: GlobalConstant.SMONEY_LOGIN_UNAPPROVED);
							memberService.updateLoginDate(member.getId());
							mv.setViewName("redirect:/");// 登录成功 重定向到
															// 首页redirect:/ ?
															// 个人中心

							// mv.addObject("cash", member.getCash());
							// mv.addObject("coupon", member.getCoupon());
							// mv.addObject("deposit", member.getDeposit());
							// mv.addObject("redeem", member.getRedeem());
							// mv.addObject("order", member.getOrder());
							// mv.addObject("check_ins", member.getCheck_ins());
							// mv.addObject("messages", member.getMessages());
							//
							session.setAttribute("isAuthenticated", true);// 标识账号密码登录
							// rememberMe = rememberMe == null ? false :
							// rememberMe;
							// if(rememberMe) {
							// /* 存放 Cookie */
							// Cookie namecookie = new Cookie("authUser",
							// URLEncoder.encode(loginname,"UTF-8") + "^" +
							// member.getPassword());
							// //生命周期
							// namecookie.setMaxAge(60 * 60 * 24 * 15);
							// //设置哪个域名写cookie
							// // namecookie.setDomain("http://127.0.0.1:8080");
							// namecookie.setPath("/index");
							// namecookie.setSecure(true);
							// response.addCookie(namecookie);
							// } else {
							// Cookie namecookie = new Cookie("authUser", null);
							// namecookie.setMaxAge(0);
							// namecookie.setPath("/index");
							// namecookie.setSecure(true);
							// response.addCookie(namecookie);
							// }
						} else {
							mv.addObject("msg", "您的账号已经被锁定");//
							mv.setViewName("/login.jsp");
						}
					} else {
						mv.addObject("msg", "密码不正确");//
						mv.setViewName("/login.jsp");
						errorcount++;
					}
				} else {
					mv.addObject("msg", "用户名或密码错误");//
					mv.setViewName("/login.jsp");
					errorcount++;
				}
				if (errorcount > 5) {
					mv.addObject("errorcount", "8");
					mv.setViewName("/login.jsp");
				}
				session.setAttribute("user:" + loginname
						+ ":passworderrorcount", errorcount);
			} else {
				mv.addObject("msg", str);
				mv.setViewName("/login.jsp");
			}
		} catch (Exception e) {
			mv.addObject("msg", "服务器忙，请稍后再试!");
			mv.setViewName("/login.jsp");
			BaseLog.e(this.getClass(), "login  用户登录失败", e);
		}

		mv.addObject("loginname", loginname);

		return mv;
	}

	/**
	 * @description 登录，先校验输入信息是否合法
	 * @author: wuzhiliang
	 * @date: 2012-10-15
	 * @return:{ "00":"服务器忙，请稍后再试!", "-1":"请输入您的用户名或手机号或邮箱!", "02":"请输入您的密码!",
	 *           "03":"请输入验证码!", "04":"验证码错误，请重新输入!", "05":"您输入的用户不存在，请重新输入!",
	 *           "06":"您的账号已经被锁定,24小时内禁止登录!", "07":"您的帐号未被激活，请问是否现在激活!",
	 *           "08":"密码错误，连续输入5次错误密码帐户  需要输入验证码", "09":"您的账号已经被锁定，请联系客服解决!",
	 *           "10":"您输入的账户已经被禁用，请联系客服解决!", "99":"登录成功!"
	 *           }/web/login/forLogin?username
	 *           =aaa&password=123456&code=1234&url=index.jsp
	 */
	@RequestMapping("/login")
	public ModelAndView login(String loginname, String loginpwd, String url,
			Boolean rememberMe, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		String str = "";
		try {
			Object obj = session.getAttribute("user:" + loginname
					+ ":passworderrorcount");
			int errorcount = 0;
			if (!StringUtil.isNullOrEmpty(obj)) {
				errorcount = (Integer) obj;
			}
			/* 校验输入信息是否合法 */
			// memberService
			// str = checkUserLogin(loginname, loginpwd, code);
			if ("".equals(str)) {
				Member member = memberService.findMemberByUsername(loginname);

				if (null != member) {
					if ("1".equals(member.getUserType())) {// 移动端 暂时不支持企业用户登录
						mv.addObject("msg", "此版本暂不支持企业会员访问");//
						mv.setViewName(super.t + "/login.jsp");
						return mv;
					}
					if (SafeUtil.md5(loginpwd).substring(8, 16)
							.equals(member.getPassword())) {
						if ("0".equals(member.getStatus())) {
							/* 登录成功 保存会员信息到session 并 返回 */
							String mobile = member.getMobile();
							if (!StringUtil.isNullOrEmpty(mobile)) {
								mobile = mobile.substring(0, 3)
										+ "*****"
										+ mobile.substring(mobile.length() - 3,
												mobile.length());
								member.setMobile(mobile);
							}

							session.setAttribute("user", member);
							String date;
							if (member.getLastLoginDate() != null
									&& (date = member.getLastLoginDate()
											.replaceAll("[^\\d]", "")).length() >= 8
									&& Integer.parseInt(date.substring(0, 8)) < Integer
											.parseInt(DateUtil
													.getCurrentDate(DateUtil._DEFAULT3)))
								memberService
										.updateMoney(
												member.getId(),
												"1".equals(member.getApprove()) ? GlobalConstant.SMONEY_LOGIN_APPROVED
														: GlobalConstant.SMONEY_LOGIN_UNAPPROVED);
							memberService.updateLoginDate(member.getId());
							mv.setViewName("redirect:/");// 登录成功 重定向到 首页

							session.setAttribute("isAuthenticated", true);// 标识账号密码登录
							rememberMe = rememberMe == null ? false
									: rememberMe;
							if (rememberMe) {
								/* 存放 Cookie */
								Cookie namecookie = new Cookie("authUser",
										URLEncoder.encode(loginname, "UTF-8")
												+ "^" + member.getPassword());
								// 生命周期
								namecookie.setMaxAge(60 * 60 * 24 * 15);
								// 设置哪个域名写cookie
								// namecookie.setDomain("http://127.0.0.1:8080");
								namecookie.setPath("/");
								namecookie.setSecure(true);
								response.addCookie(namecookie);
							} else {
								Cookie namecookie = new Cookie("authUser", null);
								namecookie.setMaxAge(0);
								namecookie.setPath("/");
								namecookie.setSecure(true);
								response.addCookie(namecookie);
							}
						} else {
							mv.addObject("msg", "您的账号已经被锁定");//
							mv.setViewName(super.t + "/login.jsp");
						}
					} else {
						mv.addObject("msg", "密码不正确");//
						mv.setViewName(super.t + "/login.jsp");
						errorcount++;
					}
				} else {
					mv.addObject("msg", "用户名或密码错误");//
					mv.setViewName(super.t + "/login.jsp");
					errorcount++;
				}
				if (errorcount > 5) {
					mv.addObject("errorcount", "8");
					mv.setViewName(super.t + "/login.jsp");
				}
				session.setAttribute("user:" + loginname
						+ ":passworderrorcount", errorcount);
			} else {
				mv.addObject("msg", str);
				mv.setViewName(super.t + "/login.jsp");
			}
		} catch (Exception e) {
			mv.addObject("msg", "服务器忙，请稍后再试!");
			mv.setViewName(super.t + "/login.jsp");
			BaseLog.e(this.getClass(), "login  用户登录失败", e);
		}
		return mv;
	}

	/**
	 * 用户退出登录
	 */
	@RequestMapping("/quit")
	public ModelAndView quit() {
		ModelAndView mv = new ModelAndView("redirect:/");
		session.removeAttribute("user");
		session.invalidate();
		return mv;
	}

	/**
	 * 忘记密码
	 */
	@RequestMapping("/forgetpwd")
	public ModelAndView forgetpwd(String mobile, String authcode,
			String password) {
		ModelAndView mv = new ModelAndView(super.t + "/forgetPwd.jsp");
		try {
			if (!(authcode == null || "".equals(authcode.trim()))) {
				String phonecode = (String) session
						.getAttribute(GlobalConstant._PHONECODE);

				if (phonecode != null && authcode.equals(phonecode)) {
					memberService.updatepwd(mobile, SafeUtil.md5(password)
							.substring(8, 16));
					session.invalidate();
					// 找回成功跳转到 登录页面并提示
					mv.addObject("msg", "密码找回成功");//
					mv.setViewName(super.t + "/login.jsp");
				} else {
					mv.addObject("msg", "手机号码不存在");
				}
			} else {
				mv.addObject("msg", "手机短信验证码不正确");
			}
		} catch (BaseException e) {
			BaseLog.e(this.getClass(), "updResetPwd:密码修改有误", e);
		}
		return mv;
	}

}